﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithm.Easy_21_MergeTwoOrderedLinkedLists
{
    class MainProject
    {
        //合并两个有序链表
        //完成
        static void Main(string[] args)
        {
            ListNode l1 = new ListNode(1,new ListNode(2,new ListNode(4)));
            ListNode l2 = new ListNode(1,new ListNode(3,new ListNode(4)));
            ListNode listNode = MergeTwoLists(l1, l2);
            while (listNode.next!=null)
            {
                Console.WriteLine(listNode.val);
                listNode = listNode.next;
            }
            //Console.WriteLine(listNode.val);
            Console.ReadKey();
        }
        public static ListNode MergeTwoLists(ListNode l1, ListNode l2)
        {
            if (l1 == null)
            {
                return l2;
            }
            else if (l2 == null)
            {
                return l1;
            }

            ListNode listNode = null;
            if (l1.val < l2.val)
            {
                listNode = new ListNode(l1.val);
                l1 = l1.next;
            }
            else
            {
                listNode = new ListNode(l2.val);
                l2 = l2.next;
            }

            ListNode temp = listNode;

            GetMinValue(l1,l2, temp);

            //ListNode listNode = new
            return listNode;
        }

        public static ListNode GetMinValue(ListNode l1, ListNode l2, ListNode l3)
        {

            if (l1 == null && l2 != null)
            {
                l3.next = new ListNode(l2.val);
                l3 = l3.next;
                l2 = l2.next;
                return GetMinValue(l1, l2, l3);
            }
            else if (l2 == null && l1 != null)
            {
                l3.next = new ListNode(l1.val);
                l3 = l3.next;
                l1 = l1.next;
                return GetMinValue(l1, l2, l3);
            }
            else if (l2 == null && l1 == null)
            {
                return l3;
            }
            if (l1.val<l2.val)
            {
                l3.next = new ListNode(l1.val);
                l3 = l3.next;
                l1 = l1.next;
            }
            else
            {
                l3.next = new ListNode(l2.val);
                l3 = l3.next;
                l2 = l2.next;
            }
            return GetMinValue(l1, l2, l3);
        }
    }

    

    public class ListNode
    {
         public int val;
         public ListNode next;
         public ListNode(int val = 0, ListNode next = null)
         {
            this.val = val;
            this.next = next;
         }
    }

}
